<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of User
 *
 * @author agama
 */
namespace org\copperforest\oak\authorization;

use \org\copperforest\oak as ct;

class User extends \org\copperforest\authentication\User
{

    private $rolSet;

    function __construct( $id )
    {
        $this->id = $id;

        $result = ct\CT::$PDO->query( 'SELECT rol FROM ct_user_rol WHERE user=' . $id,
                PDO::FETCH_NUM );

        foreach ( $result as $r ) $tags[ ] = $r[ 0 ];

        $this->rolSet = $tags;
    }

    function addRol( $tag )
    {

        if ( is_array( $tag ) ) $tags = array_diff( $tag, $this->rolSet );
        else $tags = array_diff( array( $tag ), $this->rolSet );

        if ( !empty( $tags ) ) {

            $sql = array( );

            foreach ( $tags as $t )
                    $sql[ ] = '(' . $this->id . ',' . ct\CT::$PDO->quote( $t ) . ')';

            ct\CT::$PDO->execute( 'INSERT INTO ct_user_rol ( user, tag ) VALUES ' . implode( ',',
                            $sql ) );

            $this->rolSet = array_merge( $tags, $this->rolSet );
            sort( $this->rolSet );
        }
    }

    function removeRol( $tag )
    {

        if ( is_array( $tag ) ) $tags = array_intersect( $tag, $this->rolSet );
        else $tags = array_intersect( array( $tag ), $this->rolSet );


        if ( !empty( $tags ) ) {

            $sql = array( );

            foreach ( $tags as $t ) $sql[ ] = ct\CT::$PDO->quote( $t );

            ct\CT::$PDO->execute( 'DELETE FROM ct_user_rol WHERE user=' . $this->id . ' AND tag IN (' . implode( ',',
                            $sql ) . ')' );

            $this->rolSet = array_diff( $this->rolSet, $tags );
        }
    }

    static function __deploy( $engine )
    {
        ct\CT::$PDO->exec(
                'CREATE TABLE `ct_user_rol` (
                `user` int(11) NOT NULL,
                `tag` varchar(50) NOT NULL,
                PRIMARY KEY (`user`,`tag`)
            ) ENGINE=' . $engine . ' DEFAULT CHARSET=ascii' );
    }

}

?>
